import traceback
import uuid

from applications.configs.common import V2RAY_CONFIG_FILE, V2RAY_URL
from applications.extends.V2rayUtils.v2ray import V2rayUtils
from applications.models import Session
from applications.models.v2ray import V2rayUserList
from applications.schemas.V2ray import V2rayUsers


# 获取v2ray 用户列表
def get_v2ray_user_list():
    session = Session()
    try:
        # 获取主用户
        main_user = session.query(V2rayUserList).filter(V2rayUserList.is_main == 1).first()
        if not main_user:
            return []

        # 获取全部用户
        user_list = session.query(V2rayUserList).all()
        data = [V2rayUsers.from_orm(u).dict() for u in user_list]

        # 创建协议地址
        util = V2rayUtils()
        for d in data:
            d["url"] = util.create_protocol_url(d["name"], d["user_id"], main_user.user_id)

        return data
    except Exception:
        print("获取v2ray 用户列表 异常", traceback.format_exc())
    finally:
        session.close()

    return []


# 同步用户
def synchronous_users():
    session = Session()
    try:
        # 读取配置
        util = V2rayUtils()
        config = util.ftp_read_content()
        # clients
        clients = config["inbounds"][0]["settings"]["clients"]
        # 修改所有用户
        session.query(V2rayUserList).update({"enable": 0})
        # 同步用户
        path = config["inbounds"][0]["streamSettings"]["wsSettings"]["path"]
        # 端口
        port = config["inbounds"][0]["port"]
        for client in clients:
            user = session.query(V2rayUserList).filter(V2rayUserList.user_id == client["id"]).first()
            if not user:
                url = util.create_protocol_url(client["id"], client["id"], path)
                user = V2rayUserList(user_id=client["id"], name=client["id"], url=url, is_main=0, enable=1, port=port)
                session.add(user)
            else:
                user.url = util.create_protocol_url(user.name, user.user_id, path)
                user.enable = 1

        session.commit()
    except Exception:
        print("同步用户 异常", traceback.format_exc())
        session.rollback()
        return False, "同步失败"
    finally:
        session.close()

    return True, "同步成功"


# 添加用户
def add_users(data):
    session = Session()
    try:
        # 修改所有用户
        user = session.query(V2rayUserList).filter_by(name=data.name).first()
        if user:
            return False, "用户已存在"
        # 获取主用户
        main_user = session.query(V2rayUserList).filter_by(is_main=1).first()
        if not main_user:
            return False, "请先同步信息"
        # 旧用户数据
        old_users = session.query(V2rayUserList).filter_by(enable=1).all()
        # 新增用户
        user_id = str(uuid.uuid4())
        util = V2rayUtils()
        user_url = util.create_protocol_url(data.name, user_id, main_user.id)
        user = V2rayUserList(name=data.name, user_id=user_id, url=user_url, is_main=0, enable=1)
        session.add(user)
        session.commit()
        # 获取全部用户并生成配置
        clients = [{"id": u.user_id} for u in old_users]
        clients.append({"id": user_id})
        configs = {
            "inbounds": [
                {
                    "tag": V2RAY_CONFIG_FILE,
                    "port": main_user.port,
                    "listen": "127.0.0.1",
                    "protocol": "vmess",
                    "settings": {"clients": clients},
                    "streamSettings": {
                        "network": "ws", "security": "none",
                        "wsSettings": {"path": f"/{main_user.user_id}", "headers": {"Host": V2RAY_URL}}
                    },
                    "sniffing": {"enabled": True, "destOverride": ["http", "tls"]}
                }
            ]
        }
        util.ftp_write_content(configs)

    except Exception:
        session.rollback()
        print("添加用户 异常", traceback.format_exc())
        return False, "添加失败"
    finally:
        session.close()

    return True, "添加成功"